package channel

import (
	"github.com/gin-gonic/gin"

	"gitee.com/csingo/cContext"
	"gitee.com/csingo/cLog"

	"gitee.com/csingo/cEvent/interfaces"
)

type Driver struct {
	event interfaces.Event
	db    chan any

	Size uint
}

func (i *Driver) LoadDriver(event interfaces.Event) {
	i.event = event
	if i.db == nil {
		i.db = make(chan any, i.Size)
	}
}

func (i *Driver) Publish(ctx *gin.Context, data any) {
	i.db <- data
}

func (i *Driver) Subscribe() {
	cLog.WithContext(nil, map[string]any{
		"source": "cEvent.channel.Consume",
		"app":    i.event.App,
		"name":   i.event.Name,
	}, []cLog.Option{
		cLog.IncludePaths{},
	}).Trace("启动事件订阅")
	go func() {
		for {
			select {
			case data := <-i.db:
				ctx := cContext.New()
				cLog.WithContext(ctx, map[string]any{
					"app":  i.event.App,
					"name": i.event.Name,
					"data": data,
				}).Debug("消费事件")
				if err := i.event.Handler(ctx, data); err != nil {
					cLog.WithContext(ctx, map[string]any{
						"source": "cEvent.channel.Consume",
						"app":    i.event.App,
						"name":   i.event.Name,
						"err":    err.Error(),
					}).Error("事件处理失败")
				}
			}
		}
	}()
}
